package com.trailwalker.traceability.net.interceptor;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.reflect.TypeToken;
import com.trailwalker.JavaUtils.log.LogUtils;
import com.trailwalker.JavaUtils.string.StringUtils;
import com.trailwalker.traceability.util.GsonUtils;
import okhttp3.HttpUrl;
import okhttp3.Request;

import java.util.Map;
import java.util.Set;

public class InterceptorTool {
    private static InterceptorTool ourInstance = new InterceptorTool();

    public static InterceptorTool getInstance() {
        return ourInstance;
    }

    private static final String TAG = InterceptorTool.class.getSimpleName();

    private InterceptorTool() {
    }

    public String customParams(Request originalRequest, HttpUrl.Builder builder) {

        Set<String> parameterNames = originalRequest.url().queryParameterNames();
        JSONObject params = new JSONObject();
        try {
            for (String parameterName : parameterNames) {
                String parameterValue = originalRequest.url().queryParameter(parameterName);
                if (!StringUtils.isEmpty(parameterValue)
                        && parameterValue.contains("{")
                        && GsonUtils.isGoodJson(parameterValue)) {
                    params.put(parameterName, new JSONObject(GsonUtils.loadAs(parameterValue, new TypeToken<Map<String, String>>() {
                    }.getType())));
                } else {
                    params.put(parameterName, parameterValue);
                }
                builder.removeAllQueryParameters(parameterName);
            }
        } catch (Exception e) {
            e.printStackTrace();
            LogUtils.logE(e);
        }
        return params.toString();
    }


    public JSONObject formatBody(String formatDataKey, String bodyString) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject = new JSONObject(GsonUtils.loadAs(bodyString, new TypeToken<Map<String, String>>() {
            }.getType()));
            int result = jsonObject.getInteger("result");
            jsonObject.put("json", bodyString);
            if (result == 0) {
                jsonObject.put("message", "成功");
            } else {
                jsonObject.put("message", "失败:" + result);
            }
            if (jsonObject.containsKey(formatDataKey)) {
                jsonObject.put("data", jsonObject.get(formatDataKey));
                jsonObject.remove(formatDataKey);
            }
        } catch (JSONException e) {
            System.err.println("JSONException >>> " + e);
            LogUtils.logE(e);
        } catch (Exception e) {
            System.err.println("Exception >>> " + e);
            LogUtils.logE(e);
        }
        return jsonObject;
    }

}
